import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Box,
  Button,
  TextField,
  Typography,
  Container,
  Alert,
  CircularProgress,
  Paper,
  Link,
} from '@mui/material'
import { auth, users } from '../services/api'

export default function LoginPage() {
  const navigate = useNavigate()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [email, setEmail] = useState('')
  const [fullName, setFullName] = useState('')
  const [isRegister, setIsRegister] = useState(false)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setLoading(true)

    try {
      if (isRegister) {
        // 注册
        await auth.register(username, email, password, fullName)
        // 注册成功后自动登录
        const response = await auth.login(username, password)
        if (response.data.access_token) {
          localStorage.setItem('token', response.data.access_token)
          
          // 获取用户信息
          const userResponse = await users.getMe()
          localStorage.setItem('user', JSON.stringify(userResponse.data))
          
          navigate('/')
        } else {
          setError('登录失败：未获取到访问令牌')
        }
      } else {
        // 登录
        const response = await auth.login(username, password)
        if (response.data.access_token) {
          localStorage.setItem('token', response.data.access_token)
          
          // 获取用户信息
          const userResponse = await users.getMe()
          localStorage.setItem('user', JSON.stringify(userResponse.data))
          
          navigate('/')
        } else {
          setError('登录失败：未获取到访问令牌')
        }
      }
    } catch (err: any) {
      console.error('登录/注册失败:', err)
      setError(err.response?.data?.detail || '操作失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Container component="main" maxWidth="xs">
      <Box
        sx={{
          marginTop: 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Paper
          elevation={3}
          sx={{
            padding: 4,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            width: '100%',
          }}
        >
          <Typography component="h1" variant="h5">
            {isRegister ? '注册' : '登录'}
          </Typography>
          {error && (
            <Alert severity="error" sx={{ width: '100%', mt: 2 }}>
              {error}
            </Alert>
          )}
          <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1, width: '100%' }}>
            <TextField
              margin="normal"
              required
              fullWidth
              id="username"
              label="用户名"
              name="username"
              autoComplete="username"
              autoFocus
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
            {isRegister && (
              <>
                <TextField
                  margin="normal"
                  required
                  fullWidth
                  id="email"
                  label="邮箱"
                  name="email"
                  autoComplete="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
                <TextField
                  margin="normal"
                  required
                  fullWidth
                  id="fullName"
                  label="姓名"
                  name="fullName"
                  autoComplete="name"
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                />
              </>
            )}
            <TextField
              margin="normal"
              required
              fullWidth
              name="password"
              label="密码"
              type="password"
              id="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
              disabled={loading}
            >
              {loading ? <CircularProgress size={24} /> : isRegister ? '注册' : '登录'}
            </Button>
            <Box sx={{ textAlign: 'center' }}>
              <Link
                component="button"
                variant="body2"
                onClick={() => setIsRegister(!isRegister)}
                sx={{ cursor: 'pointer' }}
              >
                {isRegister ? '已有账号？登录' : '没有账号？注册'}
              </Link>
            </Box>
          </Box>
        </Paper>
      </Box>
    </Container>
  )
} 